package com.shouxue.dragrvdemo;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.desaysv.dragrvitem.adapter.BaseItemAdapter;
import com.desaysv.dragrvitem.adapter.holder.BaseViewHolder;
import com.desaysv.dragrvitem.adapter.holder.BaseViewHolderManager;
import com.desaysv.dragrvitem.animation.RemoveItemAnimation;
import com.desaysv.dragrvitem.helper.ItemDragHelper;
import com.desaysv.dragrvitem.helper.ViewScaleHelper;
import com.desaysv.dragrvitem.item.UniqueItemManager;
import com.desaysv.dragrvitem.listener.OnItemClickListener;
import com.desaysv.dragrvitem.listener.OnItemDragListener;
import com.desaysv.dragrvitem.listener.OnItemLongClickListener;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;

import static com.desaysv.dragrvitem.listener.OnItemDragListener.MAX_ADD_SHORTCUT;

/**
 * @author COT, uidq5175
 * Time: 2024-2-19 16:30
 * Description:可以跨rv拖拽的快捷按钮容器
 * todo  还有快速点击bug
 * Copyright (c) 2024 Desaysv All rights reserved.
 */
public class DragShortcutView extends ConstraintLayout {
    private final String TAG = DragShortcutView.class.getSimpleName();

    private final Context mContext;

    private RecyclerView rvDragParent;

    private RecyclerViewManager managerNotUsed;
    private RecyclerViewManager managerAdd;

    private BaseItemAdapter mAdapter;
    private ItemDragHelper mDragHelper;
    private ViewScaleHelper mScaleHelper;

    private AddOrDeleteListener mAddOrDeleteListener;
    private final String ADD = "Add";
    private final String NOT_USED = "NotUsed";

    public interface AddOrDeleteListener {
        //添加侧的回调
        void usedAddOrDeleteShortcut(int usedSize);

        //全部侧的回调
        void allAddOrDeleteShortcut(int allSize);
    }

    public DragShortcutView(@NonNull Context context) {
        this(context, null);
    }

    public DragShortcutView(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public DragShortcutView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.mContext = context;
//        initView();
    }

    public void setAddOrDeleteListener(AddOrDeleteListener addOrDeleteListener) {
        mAddOrDeleteListener = addOrDeleteListener;
        initView();
    }

    private void initView() {
        Log.i(TAG, "initView: DragShortcutView");
        inflate(mContext, R.layout.view_drag_item, this);
        rvDragParent = findViewById(R.id.rv_drag_parent);

        mAdapter = new BaseItemAdapter();
        //此处为了简单所以使用不可复用的模式，正式业务视具体情况而定！！！
        managerNotUsed = new RecyclerViewManager(3,true);
        managerAdd = new RecyclerViewManager(3,false);
        mAdapter.addDataItems(Arrays.asList(new UniqueItemManager(managerAdd), new UniqueItemManager(managerNotUsed)));
        //设置横向滚动LinearLayoutManager
        NoScrollLinearManager linearManager = new NoScrollLinearManager(mContext, RecyclerView.HORIZONTAL, false);
        linearManager.setScrollEnabled(false);
        rvDragParent.setLayoutManager(linearManager);
        rvDragParent.setAdapter(mAdapter);

        //添加分割线
        rvDragParent.addItemDecoration(new RecycleViewGridDivider(30,
                0, true, RecycleViewGridDivider.HORIZONTAL));
        //去掉光晕
        rvDragParent.setOverScrollMode(View.OVER_SCROLL_NEVER);

        //ItemDragHelper，需要传入外层的横向滚动的RecyclerView
        mDragHelper = new ItemDragHelper(rvDragParent, GlobalConstants.TRANSPARENT_PANEL_WINDOW_TYPE);
        mDragHelper.setOnItemDragListener(new OnBaseDragListener());

        mScaleHelper = new ViewScaleHelper();
        //设置最外层的Content视图
        mScaleHelper.setContentView(this);
        //设置横向的Recycler列表视图
        mScaleHelper.setHorizontalView(rvDragParent);

        managerAdd.mItemAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(BaseViewHolder viewHolder) {
                if (mDragHelper.isDrag()) {
                    //防止触摸时点击快捷方式出现错误
                    return;
                }
                managerAdd.mItemAdapter.removeDataItem(viewHolder.getItemPosition());
                BaseSVShortcutImp shortcutImp = (BaseSVShortcutImp) viewHolder.getItemData();
                //更新加减标记
                shortcutImp.setAdded(false);
                if (!managerNotUsed.getDataItems().contains(shortcutImp)) {
                    managerNotUsed.mItemAdapter.addDataItem(shortcutImp);
                }
                if (mAddOrDeleteListener != null) {
                    mAddOrDeleteListener.usedAddOrDeleteShortcut(managerAdd.getDataItems().size());
                }
                if (mAddOrDeleteListener != null) {
                    mAddOrDeleteListener.allAddOrDeleteShortcut(managerNotUsed.getDataItems().size());
                }
            }
        });
        managerNotUsed.mItemAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(BaseViewHolder viewHolder) {
                if (mDragHelper.isDrag()) {
                    //防止触摸时点击快捷方式出现错误
                    return;
                }
                if (managerAdd.getDataItems().size() >= MAX_ADD_SHORTCUT) {
                    Toast.makeText(mContext, String.format(Locale.getDefault(),
                            getResources().getString(R.string.max_function),MAX_ADD_SHORTCUT), Toast.LENGTH_SHORT).show();
                    return;
                }
                managerNotUsed.mItemAdapter.removeDataItem(viewHolder.getItemPosition());
                BaseSVShortcutImp shortcutImp = (BaseSVShortcutImp) viewHolder.getItemData();
                //更新加减标记
                shortcutImp.setAdded(true);
                if (!managerAdd.getDataItems().contains(shortcutImp)) {
                    managerAdd.mItemAdapter.addDataItem(shortcutImp);
                }
                if (mAddOrDeleteListener != null) {
                    mAddOrDeleteListener.usedAddOrDeleteShortcut(managerAdd.getDataItems().size());
                }
                if (mAddOrDeleteListener != null) {
                    mAddOrDeleteListener.allAddOrDeleteShortcut(managerNotUsed.getDataItems().size());
                }
            }
        });
    }

    public void setData(@NonNull List<?> dataAddItems, @NonNull List<?> dataNotItems) {
        managerAdd.setData(dataAddItems);
        managerNotUsed.setData(dataNotItems);
    }

    public void scrollToPosition0() {
        if (managerAdd.getRecyclerView() != null) {
            managerAdd.getRecyclerView().scrollToPosition(0);
        }
        if (managerNotUsed.getRecyclerView() != null) {
            managerNotUsed.getRecyclerView().scrollToPosition(0);
        }
    }

    public List<BaseSVShortcutImp> getAddData() {
        Log.d(TAG, "getAddData: " + managerAdd.getDataItems().size());
        return (List<BaseSVShortcutImp>) managerAdd.getDataItems();
    }

    public List<BaseSVShortcutImp> getNotUsedData() {
        Log.d(TAG, "getNotUsedData: " + managerNotUsed.getDataItems().size());
        return (List<BaseSVShortcutImp>) managerNotUsed.getDataItems();
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        //需要把touch事件传给dragHelper，true表示消耗掉事件
        //需要保证在Activity或者外层的ViewGroup或可以拦截Touch事件的地方回调都可以
        return mDragHelper.onTouch(ev) || super.dispatchTouchEvent(ev);
    }

    class OnBaseDragListener extends OnItemDragListener {

        @Override
        public float getScale() {
            return mScaleHelper.isInScaleMode() ? mScaleHelper.getScale() : super.getScale();
        }

        @Override
        public void onDragFinish(RecyclerView recyclerViewParent, RecyclerView recyclerView, int itemRecyclerPos, int itemPos) {
            super.onDragFinish(recyclerViewParent, recyclerView, itemRecyclerPos, itemPos);
            Log.d(TAG, "onDragFinish: itemRecyclerPos = " + itemRecyclerPos + " ,itemPos = " + itemPos);
            MarqueeSwitch marqueeSwitch = null;
            if (recyclerView != null && recyclerView.findViewHolderForAdapterPosition(itemPos) != null) {
                RecyclerView.ViewHolder viewHolder = recyclerView.findViewHolderForAdapterPosition(itemPos);
                if (null != viewHolder) {
                    marqueeSwitch = (MarqueeSwitch) viewHolder.itemView;
                }
            } else {
                View childView = recyclerViewParent.getChildAt(itemRecyclerPos);
                if (childView instanceof RecyclerView) {
                    RecyclerView childRecyclerView = (RecyclerView) childView;
                    for (int j = 0; j < childRecyclerView.getChildCount(); j++) {
                        View view = childRecyclerView.getChildAt(j);
                        if (view instanceof MarqueeSwitch) {
                            marqueeSwitch = (MarqueeSwitch) view;
                            if (marqueeSwitch.isDragMode()) {
                                break;
                            }
                        }
                    }
                }
            }
            if (null != marqueeSwitch) {
                try {
                    if (itemRecyclerPos == 1) {
                        //会触发这个DragShortcutManager.onBindViewHolder，然后当时数据的isAddeds属性还是false，需要在某个地方修改isAdded属性为true
                        BaseSVShortcutImp baseSVShortcutImp = (BaseSVShortcutImp) managerNotUsed.mItemAdapter.getDataList().get(itemPos);
                        baseSVShortcutImp.setAdded(false);
                    } else {
                        BaseSVShortcutImp baseSVShortcutImp = (BaseSVShortcutImp) managerAdd.mItemAdapter.getDataList().get(itemPos);
                        baseSVShortcutImp.setAdded(true);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
                marqueeSwitch.setDragMode(false);
                marqueeSwitch.setEditMode(true, itemRecyclerPos == 1);
                //刷新整个未添加（未使用）的列表，避免超过可见范围的item出现不显示的问题
                managerAdd.mItemAdapter.notifyDataSetChanged();
                managerNotUsed.mItemAdapter.notifyDataSetChanged();
            }

            if (mAddOrDeleteListener != null) {
                mAddOrDeleteListener.usedAddOrDeleteShortcut(managerAdd.getDataItems().size());
            }
            if (mAddOrDeleteListener != null) {
                mAddOrDeleteListener.allAddOrDeleteShortcut(managerNotUsed.getDataItems().size());
            }
        }

        @Override
        public void onDragFail() {
            super.onDragFail();
            Toast.makeText(mContext, String.format(Locale.getDefault(),
                    getResources().getString(R.string.max_function),MAX_ADD_SHORTCUT), Toast.LENGTH_SHORT).show();

        }
    }

    public boolean isDrag() {
        if (mDragHelper == null) {
            return false;
        }
        return mDragHelper.isDrag();
    }

    class RecyclerViewManager extends BaseViewHolderManager<UniqueItemManager> {
        //网格的 列数
        private final int spanCount;

        private final BaseItemAdapter mItemAdapter;
        private RecyclerView recyclerView;
        private boolean isNotUsed;

        RecyclerViewManager(int spanCount,boolean isNotUsed) {
            this.spanCount = spanCount;
            this.isNotUsed = isNotUsed;
            mItemAdapter = new BaseItemAdapter();
        }

        @Override
        protected void onCreateViewHolder(@NonNull BaseViewHolder holder) {
            super.onCreateViewHolder(holder);
            View view = holder.itemView;

            mScaleHelper.addVerticalView(view);
            recyclerView = getView(view, R.id.rv_shortcut);
            if (isNotUsed) {
                recyclerView.setTag(NOT_USED);
            } else {
                recyclerView.setTag(ADD);
            }

            recyclerView.setLayoutManager(new GridLayoutManager(view.getContext(), spanCount));
            //为XXBean数据源注册XXHolderManager管理类 数据源必须实现ItemData接口
            mItemAdapter.register(BaseSVShortcutImp.class, new DragShortcutManager());
            //去掉光晕
            recyclerView.setOverScrollMode(View.OVER_SCROLL_NEVER);
            recyclerView.setAdapter(mItemAdapter);
            //添加分割线
//            DividerItemDecoration itemDecorationHORIZONTAL = new DividerItemDecoration(getContext(), GridLayoutManager.HORIZONTAL);
//            itemDecorationHORIZONTAL.setDrawable(ContextCompat.getDrawable(getContext(), R.drawable.shape_divider));
//            DividerItemDecoration itemDecorationVERTICAL = new DividerItemDecoration(getContext(), GridLayoutManager.VERTICAL);
//            itemDecorationVERTICAL.setDrawable(ContextCompat.getDrawable(getContext(), R.drawable.shape_divider));
//            recyclerView.addItemDecoration(itemDecorationHORIZONTAL);
//            recyclerView.addItemDecoration(itemDecorationVERTICAL);

            //设置item动画
            DefaultItemAnimator defaultItemAnimator = new RemoveItemAnimation();
            defaultItemAnimator.setRemoveDuration(500);
            recyclerView.setItemAnimator(defaultItemAnimator);

            mItemAdapter.setOnItemLongClickListener(new OnItemLongClickListener() {
                @Override
                protected void onItemLongClick(BaseViewHolder viewHolder) {
                    if (!mDragHelper.isDrag()) {
                        //2024.03.22 防止多个快捷方式同时变可拖拽
                        //2024.05.18 防止多个手指同时按下触发拖拽
                        if (mDragHelper.getPointerCount() == 1) {
                            MarqueeSwitch marqueeSwitch = (MarqueeSwitch) viewHolder.itemView;
                            marqueeSwitch.setDragMode(true);
                            ISVShortcut statusShortcut = (ISVShortcut) mItemAdapter.getDataList().get(viewHolder.getItemPosition());
                            statusShortcut.setAdded(false);
                            mDragHelper.startDrag(viewHolder);
                        }
                    }
                }
            });
        }

        @Override
        public void onBindViewHolder(@NonNull BaseViewHolder holder, @NonNull UniqueItemManager data) {
        }

        @Override
        protected int getItemLayoutId() {
            return R.layout.item_rv;
        }

        public void setData(@NonNull List<?> dataItems) {
            Log.d(TAG, "setData: " + dataItems.size());
            mItemAdapter.setDataItems(dataItems);
        }

        public List<?> getDataItems() {
            return mItemAdapter.getDataList();
        }

        public RecyclerView getRecyclerView() {
            return recyclerView;
        }
    }
}
